package com.zzedu.integration.websocket.client;

import com.ejlchina.okhttps.HTTP;
import com.ejlchina.stomp.Message;
import com.ejlchina.stomp.Stomp;
import com.google.common.collect.Lists;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 普通websocket   无 withSockJS 模式
 */
public class TestWebSocket {
    public static void main(String[] args) {


        Cookie cookie = new Cookie.Builder().name("SESSION").value("MGM3YjQ4ZDYtNzQ4MS00OTQzLTk1YWQtZGMwOWZkOTAyODAy").domain(HttpUrl.get("http://127.0.0.1:8060/commonwebsocket").host()).build();
        CookieJar cookieJar = new CookieJar() {
            List<Cookie> cache = new ArrayList<>();

            //Http请求结束，Response中有Cookie时候回调
            @Override
            public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                //内存中缓存Cookie
                cache.addAll(cookies);
            }

            //Http发送请求前回调，Request中设置Cookie
            @Override
            public List<Cookie> loadForRequest(HttpUrl url) {
                //过期的Cookie
                List<Cookie> invalidCookies = new ArrayList<>();
                //有效的Cookie
                List<Cookie> validCookies = new ArrayList<>();

                for (Cookie cookie : cache) {

                    if (cookie.expiresAt() < System.currentTimeMillis()) {
                        //判断是否过期
                        invalidCookies.add(cookie);
                    } else if (cookie.matches(url)) {
                        //匹配Cookie对应url
                        validCookies.add(cookie);
                    }
                }

                //缓存中移除过期的Cookie
                cache.removeAll(invalidCookies);

                //返回List<Cookie>让Request进行设置
                return validCookies;
            }
        };
        cookieJar.saveFromResponse(HttpUrl.get("http://127.0.0.1:8060/commonwebsocket"), Lists.newArrayList(cookie));
        HTTP http = HTTP.builder()
                .config((OkHttpClient.Builder builder) -> {
                    builder.connectTimeout(2, TimeUnit.SECONDS);
                    builder.writeTimeout(2, TimeUnit.SECONDS);
                    builder.readTimeout(2, TimeUnit.SECONDS);
                    builder.cookieJar(cookieJar);
                }).build();
        Stomp stompClient = Stomp.over(http.webSocket("ws://127.0.0.1:8060/commonwebsocket").heatbeat(20, 20));
        stompClient.connect();

        stompClient.setOnConnected(stomp ->

                {
                    // 服务器连接成功回调
                    System.out.println("====================服务器连接成功回调");
                }).

                setOnDisconnected(close ->

                {
                    System.out.println(close.getReason());
                    // 连接已断开回调
                    System.out.println("====================连接已断开回调");
                }).

                setOnError(msg ->

                {
                    // 错误监听（v2.4.1 新增）
                    // 处理服务器发出的 ERROR 帧
                    System.out.println("====================处理服务器发出的 ERROR 帧");
                })
                        .

                topic("/getResponse", (Message msg) ->

                {
                    // 得到消息负载
                    String payload = msg.getPayload();
                    System.out.println("======" + payload);
                    // 如果需要手动确认消息,调用此方法确认
                });
        while (true) {

        }
    }
}
